<?php

declare (strict_types=1);

namespace catchAdmin\monitor\command;

use catcher\facade\Http;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;
use think\facade\Log;
use catcher\Code;
use catchAdmin\basics\model\States as statesModel;
use catchAdmin\basics\model\City as cityModel;
use catchAdmin\basics\model\CityZip as cityZipModel;

class TestCommand extends Command
{
    protected $pid;

    protected function configure()
    {
        // 指令配置
        $this->setName('catch:test')
            ->setDescription('get test online list');
    }

    protected function execute(Input $input, Output $output)
    {
        try {
            $this->executeCommand();
        } catch (\Exception $e) {
            Log::error('Test Error Line:' . $e->getLine());
            print_r($e->getMessage());exit();
            return $e->getMessage();
        }
    }

    /**
     * 执行 command
     *
     * @time 2021年03月15日
     * @return void
     */
    protected function executeCommand()
    {
//        $this->insertCity();

        $this->insertCityZip();

//        $this->insertCityUnZip();

//        $cityModel = new cityModel();
//        $token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhZG1pbl9pZCI6MSwiYXVkIjoiIiwiZXhwIjoxNjM5NjIyODk4LCJpYXQiOjE2MTM3MDI4OTgsImlzcyI6IiIsImp0aSI6IjRjZGU5ODMzYTAzYzI2YTE3ODJjMDlmZGVkZDU5NmRkIiwibmJmIjoxNjEzNzAyODk4LCJzdWIiOiIifQ.jY9JB-9tvP-OmHpCJptWxqd46fad3VDRu0TIDeMPdUs';
//        foreach ($cityModel->field('name,id')->where(['postalCode'=> ''])->select() as $city){
//            $response = Http::token($token)->form([
//                'city' => $city['name'],
//                'postalCode' => ''
//            ])->post('http://192.168.1.8:8809/address/checkAddress');
//            $post = [];
//            $postalCodes = $response['data'];
//            if (!isset($postalCodes['AddressValidationResult'])){
//                $cityModel->updateBy($city['id'], ['postalCode' => 'to']);
//            }else {
//                $postalCodes = $postalCodes['AddressValidationResult'];
//                if (isset($postalCodes['PostalCodeLowEnd'])){
//                    array_push($post, $postalCodes['PostalCodeLowEnd']);
//                    array_push($post, $postalCodes['PostalCodeHighEnd']);
//                }else {
//                    foreach ($postalCodes as $postalCode) {
//                        array_push($post, $postalCode['PostalCodeLowEnd']);
//                        array_push($post, $postalCode['PostalCodeHighEnd']);
//                    }
//                }
//                $post = array_unique($post);
//                $data = [
//                    'postalCode' => implode(',', $post),
//                    'postalCode2' => \GuzzleHttp\json_encode($postalCodes)
//                ];
////            print_r($data);exit();
//                $cityModel->updateBy($city['id'], $data);
//            }
//        }

    }

    protected function insertCity()
    {
        $statesModel = new statesModel();
        $cityModel = new cityModel();
        foreach ($statesModel->field('code, id')->where(['country_code' => 'USA'])->select() as $state) {
            $citys = Db::query('select us.ID as us_id,us.STATE_CODE,uc.* from US_STATES as us 
                left join US_CITIES as uc on uc.ID_STATE = us.ID where us.STATE_CODE = "' . $state['code'] . '"');
            foreach ($citys as $city) {
//                print_r($city);exit();
                // 如果城市信息尚不存在
                if (!$cityHas = $cityModel->where(['name' => $city['CITY'], 'states_id' => $state['id']])->find()) {
                    $data = [
                        'states_id' => $state['id'],
                        'code' => '',
                        'name' => $city['CITY'],
                        'cname' => '',
                        'lower_name' => strtolower($city['CITY']),
                        'code_full' => '',
                        'lon' => $city['LONGITUDE'],
                        'lat' => $city['LATITUDE']
                    ];
                    $cityModel->createBy($data);
                } else {
                    if (!empty($cityHas['lon'])) {
                        $cityModel->updateBy($cityHas['id'], [
                            'lon' => $city['LONGITUDE'],
                            'lat' => $city['LATITUDE']
                        ]);
                    }
                }
            }
        }
    }

    protected function insertCityZip(){
        $zips = public_path().'zip.json';
        $zips = file_get_contents($zips);
        $zips = \GuzzleHttp\json_decode($zips, true);
        $statesModel = new statesModel();
        $cityModel = new cityModel();
        $cityZipModel = new cityZipModel();
        $uncity = [];
        foreach ($zips as $key => $zip){
            $res = Db::query('select c.id from city as c left join states as s on s.id = c.states_id 
                where c.lower_name = ? and s.code = ?', [strtolower($zip['fields']['city']), $zip['fields']['state']]);
            if (!isset($res[0])){
                array_push($uncity, $zip);
            }else {
                $cityZipModel->createBy([
                    'city_id' => $res[0]['id'],
                    'zip' => $zip['fields']['zip'],
                    'lon' => $zip['fields']['longitude'],
                    'lat' => $zip['fields']['latitude'],
                    'timezone' => $zip['fields']['timezone']
                ]);
            }
        }
//        file_put_contents(public_path()."/unzip2.json",\GuzzleHttp\json_encode($uncity));//写入
    }

//    protected function insertCityUnZip(){
//        $zips = file_get_contents(public_path().'unzip2.json');
//        $zips = \GuzzleHttp\json_decode($zips, true);
//        $statesModel = new statesModel();
//        $cityModel = new cityModel();
//        $cityZipModel = new cityZipModel();
//        foreach ($zips as $key => $zip){
//            $res = Db::query('select c.id from city as c left join states as s on s.id = c.states_id
//                where c.lower_name = ? and s.code = ?', [strtolower($zip['fields']['city']), $zip['fields']['state']]);
//            if (!isset($res[0])){
//                $stateId = $statesModel->where(['code' => $zip['fields']['state']])->value('id');
////                print_r( $stateId);exit();
//                $cityModel->createBy([
//                    'states_id' => $stateId,
//                    'name' => $zip['fields']['city'],
//                    'lower_name' => strtolower($zip['fields']['city']),
//                    'lon' => $zip['fields']['geopoint'][1],
//                    'lat' => $zip['fields']['geopoint'][0],
//                ]);
//            }
//        }
//    }
}
